var VSHADER_SOURCE = `
    attribute vec4 a_Position;
    void main(){
      gl_Position = a_Position;
      gl_PointSize = 10.0;
    }
  `
var FSHADER_SOURCE = `
precision mediump float;
    uniform vec4 u_Color;
    void main() {
      gl_FragColor = u_Color;
      // gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }
  `;
var canvas = document.getElementById('example');
var gl = getWebGLContext(canvas);

function drawPoint(x, y, z) {

}

function clear() {
  // Specify the color for clearing <canvas>
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  // Clear <canvas>
  gl.clear(gl.COLOR_BUFFER_BIT);
}

var g_points = [];
var g_colors = [];
function click(event) {
  var target = event.target;
  var rect = event.target.getBoundingClientRect();
  var x = event.clientX - rect.left; // x coordinate of a mouse pointer
  var y = event.clientY - rect.top; // y coordinate of a mouse pointer
  var centerX = target.width / 2,
    centerY = target.height / 2;
  var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  var u_Color = gl.getUniformLocation(gl.program, 'u_Color');
  var ox = x / centerX - 1,oy = 1 - y / centerY;
  if (!u_Color) {
    console.log('Failed to get the storage location of u_FragColor');
    return;
  }

  if (ox >= 0.0 && oy >= 0.0) {      // First quadrant
    g_colors.push([1.0, 0.0, 0.0, 1.0]);  // Red
  } else if (ox < 0.0 && oy < 0.0) { // Third quadrant
    g_colors.push([0.0, 1.0, 0.0, 1.0]);  // Green
  } else {                         // Others
    g_colors.push([1.0, 1.0, 1.0, 1.0]);  // White
  }

  // x,y
  g_points.push([ox,oy]);

  gl.clear(gl.COLOR_BUFFER_BIT);
  for (let i = 0; i < g_points.length; ++i) {
    gl.vertexAttrib3f(a_Position, g_points[i][0], g_points[i][1], 0.0);
    gl.uniform4f(u_Color,g_colors[i][0],g_colors[i][1],g_colors[i][2],g_colors[i][3]);
    gl.drawArrays(gl.POINTS, 0, 1);
  }
}

function init() {
  // Initialize shaders
  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log('Failed to intialize shaders.');
    return;
  }
  clear();
  canvas.addEventListener("click", click);
}

function main() {
  console.log("main")
  console.log(gl)
  init();
}